package cn.taobaoke.restful.controller;

import cn.taobaoke.restful.domain.PIDEntity;
import cn.taobaoke.restful.domain.RobotEntity;
import cn.taobaoke.restful.service.PIDService;
import cn.taobaoke.restful.service.RobotService;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * RobotController类.
 * +-----------------------------------------------------------------------------------------------+
 * |类名称: RobotController                                                                         |
 * |创建时间: 3/18/17                                                                               |
 * |功能简介:                                                                                       |
 * |参考链接:                                                                                       |
 * +-----------------------------------------------------------------------------------------------+
 *
 * @author luch
 */

@RestController
@RequestMapping(value = "/{domain}/{domainId}/api/robots")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class RobotController extends BaseController {

    @GetMapping("")
    public Result getAllRobots(@PathVariable Long domainId) {
        logger.debug("GET /{}/api/robots", domainId);

        List<RobotEntity> robots = robotService.getAllRobots(domainId);
        return wrapObj(robots);
    }

    @PostMapping("")
    public Result saveRobot(@PathVariable Long domainId, @RequestBody RobotEntity robot) {
        logger.debug("POST /{}/api/robots", domainId);

        robotService.createOrUpdate(robot, domainId);
        return wrapVoid();
    }

    @PostMapping("/pids")
    public Result savePids(@PathVariable Long domainId, @RequestBody List<String> pids) {
        logger.debug("POST /{}/api/robots/pids", domainId);

        pidService.createPids(pids, domainId);
        return wrapVoid();
    }

    @PostMapping("/pid")
    public Result savePid(@PathVariable Long domainId, @RequestBody Map<String, Object> data) {
        logger.debug("POST /{}/api/robots/pid", domainId);

        String pid = (String) data.get("pid");
        String account = (String) data.get("account");
        PIDEntity entity = pidService.savePidFromAlimamaRobot(pid, account, domainId);
        return wrapObj(entity);
    }

    @DeleteMapping("/{id}")
    public Result removeRobotById(@PathVariable Long domainId, @PathVariable Long id) {
        robotService.deleteById(id, domainId);
        return wrapVoid();
    }

    private final @NonNull
    RobotService robotService;

    private final @NonNull
    PIDService pidService;

    private static Logger logger = LogManager.getLogger(RobotController.class);
}
